Automaton_Sell = Automaton:NewModule("Sell", "AceEvent-2.0", "AceConsole-2.0", "AceDebug-2.0")
local module = Automaton_Sell

local L
local locale = GetLocale()
if locale == "koKR" then
	L = {
	    ["Sell"] = "아이템 판매",
		["Automatically sell all grey inventory items when at merchant"] = "상인에게 자동으로 모든 회색 품목의 아이템을 판매합니다.",
		["Ignore"] = "Ignore",
		["Items that should never be sold."] = "Items that should never be sold.",
	}
elseif locale == "esES" then
	L = {
	    ["Sell"] = "Vender",
		["Automatically sell all grey inventory items when at merchant"] = "Vende autom\195\161ticamente todos los objetos grises de tu inventario cuando est\195\161s en un vendedor",
		["Ignore"] = "Ignore",
		["Items that should never be sold."] = "Items that should never be sold.",
	}
elseif locale == "zhTW" then
	L = {
	    ["Sell"] = "清理垃圾",
		["Automatically sell all grey inventory items when at merchant"] = "與商人交易時自動賣出灰色物品",
		["Ignore"] = "Ignore",
		["Items that should never be sold."] = "Items that should never be sold.",
	}
elseif locale == "zhCN" then
	L = {
		["Sell"] = "Sell",
		["Automatically sell all grey inventory items when at merchant"] = "与商人交易时自动出售灰色的物品",
		["Ignore"] = "Ignore",
		["Items that should never be sold."] = "Items that should never be sold.",
	}
end
L = setmetatable(L or {}, { __index = function(self, key) rawset(self, key, key) return key end })

module.description = L["Automatically sell all grey inventory items when at merchant"]
module.options = {
	ignore = {
		type  = "group",
		name  = L["Ignore"],
		desc  = L["Items that should never be sold."],
		args  = {
			list = {
				type = "execute",
				name = "List",
				desc = "Print all items being ignored by Sell to the screen.",
				func = function() module:ListIgnored() end
			},
			add = {
				type  = "text",
				name  = "Add Item",
				desc  = "Add an item to be ignored, accepts item names or links. Name must be exact, and is case sensitive.",
				usage = "<item name or link>",
				get   = false,
				set   = function(v) module:IgnoreItem(v) end,
				order = 1,
			},
			remove = {
				type  = "text",
				name  = "Remove Item",
				desc  = "Removes an item from the ignore list. It must be entered exactly as it was added.",
				usage = "<item name or link>",
				get   = false,
				set   = function(v) module:RemoveIgnore(v) end,
				order = 2,
			},
			purge = {
				type = "execute",
				name = "Purge",
				desc = "Remove all items from the ignore list.",
				func = function() module:PurgeIgnored() end
			}
		},
	},
	custom = {
		type  = "group",
		name  = "Always sell",
		desc  = "Items that should always be sold.",
		args  = {
			list = {
				type = "execute",
				name = "List",
				desc = "Print all items being sold by Sell to the screen.",
				func = function() module:ListAlwaysSell() end
			},
			add = {
				type  = "text",
				name  = "Add Item",
				desc  = "Add an item to always besold, accepts item names or links. Name must be exact, and is case sensitive.",
				usage = "<item name or link>",
				get   = false,
				set   = function(v) module:AlwaysSellItem(v) end,
				order = 1,
			},
			remove = {
				type  = "text",
				name  = "Remove Item",
				desc  = "Removes an item from the always sell list. It must be entered exactly as it was added.",
				usage = "<item name or link>",
				get   = false,
				set   = function(v) module:RemoveAlwaysSell(v) end,
				order = 2,
			},
			purge = {
				type = "execute",
				name = "Purge",
				desc = "Remove all items from the always sell list.",
				func = function() module:PurgeAlwaysSell() end
			}
		},
	},
}

function module:OnInitialize()
	self.db = Automaton:AcquireDBNamespace("Sell")
    Automaton:RegisterDefaults("Sell", "profile", {
		disabled = false,
		useGarbageFu = false,
		ignore = {},
		custom = {}
    })
	self:RegisterOptions(self.options)
end

function module:OnEnable()
	self:RegisterEvent("MERCHANT_SHOW")
end

local bag, slot
function module:MERCHANT_SHOW()
	for bag = 0, 4 do
		if GetContainerNumSlots(bag) > 0 then
			for slot = 1, GetContainerNumSlots(bag) do
				local texture, itemCount, locked, quality = GetContainerItemInfo(bag, slot)
				if quality then
					local linkcolor = self:ProcessLink(GetContainerItemLink(bag, slot))
					if linkcolor == 1 and not self:IsDebugging() then
						UseContainerItem(bag, slot)
					end
				end
			end
		end
	end
end

local color, name
function module:ProcessLink(link)
	for color, name in string.gmatch(link, "(|c%x+)|Hitem:.+|h%[(.-)%]|h|r") do
		for k,v in pairs(self.db.profile.ignore) do
			if (name == v) or (link == v) then
				self:Debug("ProcessLink: %s", name)
				return 0
			end
		end
		
		for k,v in pairs(self.db.profile.custom) do
			if (name == v) or (link == v) then
				self:Debug("ProcessLink: %s", name)
				return 1
			end
		end

		if color == ITEM_QUALITY_COLORS[0].hex then
			self:Debug("ProcessLink: %s", name)
			return 1
		end
	end
	return 0
end

function module:IgnoreItem(item)
	tinsert(self.db.profile.ignore,item)
end

function module:RemoveIgnore(item)
	for k,v in pairs(self.db.profile.ignore) do
		if v == item then
			self.db.profile.ignore[k] = nil
		end
	end
end

function module:ListIgnored()
	if #self.db.profile.ignore == 0 then
		self:Print("Ignoring no items.")
	else
		self:Print("Ignoring these items:")
		for k,v in pairs(self.db.profile.ignore) do
			self:Print(v)
		end
	end
end

function module:PurgeIgnored()
	self:Print(#self.db.profile.ignore .. " items purged.")
	self.db.profile.ignore = {}
end

function module:AlwaysSellItem(item)
	tinsert(self.db.profile.custom,item)
end

function module:RemoveAlwaysSell(item)
	for k,v in pairs(self.db.profile.custom) do
		if v == item then
			self.db.profile.custom[k] = nil
		end
	end
end

function module:ListAlwaysSell()
	if #self.db.profile.custom == 0 then
		self:Print("No items are specified to always be sold.")
	else
		self:Print("Always selling these items:")
		for k,v in pairs(self.db.profile.custom) do
			self:Print(v)
		end
	end
end

function module:PurgeAlwaysSell()
	self:Print(#self.db.profile.custom .. " items purged.")
	self.db.profile.custom = {}
end